package com.iqiyi.pps.epg.web.webapp.action.auth;


import com.iqiyi.pps.epg.web.utils.Struts2Utils;
import com.iqiyi.pps.epg.web.webapp.action.BaseAction;
import com.iqiyi.pps.epg.core.dao.base.HibernateUtils;
import com.iqiyi.pps.epg.core.dao.base.Page;
import com.iqiyi.pps.epg.core.dao.base.PropertyFilter;
import com.iqiyi.pps.epg.core.exception.InvalidParametersException;
import com.iqiyi.pps.epg.core.exception.ServiceException;
import com.iqiyi.pps.epg.core.model.auth.Authority;
import com.iqiyi.pps.epg.core.model.auth.Resource;
import com.iqiyi.pps.epg.core.service.auth.AuthorityManager;
import com.iqiyi.pps.epg.core.service.auth.ResourceManager;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;

import javax.servlet.http.HttpServletRequest;
import java.util.LinkedList;
import java.util.List;

/**
 * 用户管理Action.
 * 
 * 使用Struts2 convention-plugin annotation定义Action参数.
 */
@SuppressWarnings("serial")
@Namespace("/auth/resource")
@Scope("prototype")
@Results( { @Result(name = BaseAction.RELOAD, location = "resource.action", type = "redirect") })
public class ResourceAction extends BaseAction<Resource> {

    @Autowired
    ResourceManager resourceManager;

	/* 基本属性 */
	private Resource resource;
	private Long id;
	Page<Resource> page = new Page<Resource>(15);
	private String code;
    private String message;
	// 权限相关属性
	private String authNames;
	@Autowired
    AuthorityManager authorityManager;
    @Override
    @Action(value = "input")
	public String input() throws Exception {
		return INPUT;
	}

    
	@Override
    @Action(value = "delete")
	public String delete() throws Exception {
		try {
            if (id == null) {
				throw new InvalidParametersException("参数错误: 未选中资源");
			}

			resourceManager.deleteResource(id);
            message  = "操作成功";
            code = "A00000";
		} catch (InvalidParametersException e) {
            code = "A00001";
			//addActionMessage(e.getMessage());
            message = e.getMessage();
            return "verify";

		}catch (ServiceException e){
           logger.error(e.getMessage(), e);

        }
		return "verify";
	}

	@Override
    @Action(value = "list")
	public String list() throws Exception {
		HttpServletRequest request = Struts2Utils.getRequest();
		List<PropertyFilter> filters = PropertyFilter.buildFromHttpRequest(request);

		page = resourceManager.searchResource(page, filters);
		return SUCCESS;
	}

	@Override
	protected void prepareModel() throws Exception {
		if (null == id) {
			resource = new Resource();
		} else {
			resource = resourceManager.getResource(id);
		}
	}

	@Override
    @Action(value = "save")
	public String save() throws Exception {
		
		// 遍历权限,通过多对多更新中间表

		// 得到页面传过来的所有authNames
		String[] authories = authNames.split(",");
		// 得到这些authNames对应的ID
		List<Long> checkedAuthIds = new LinkedList<Long>();
		for (String authName : authories) {
            authName = authName.substring(5);
            Authority authority = authorityManager.getAuthorityByName(authName);
            if(authority != null) {
			    checkedAuthIds.add(authority.getId());
            }
		}

		// TODO 去掉原来集合中没有的Authority
		HibernateUtils.mergeByCheckedIds(resource.getAuthorities(), checkedAuthIds, Authority.class);
       
		// 多对多更新中间表
		for (Long authId : checkedAuthIds) {
			resource.getAuthorities().add(authorityManager.getAuthority(authId));
		}
        resourceManager.saveResource(resource);


		addActionMessage("保存资源成功");
		return INPUT;
	}


    	//-- 其他Action函数 --//
	/**
	 * 支持使用Jquery.validate Ajax检验资源是否重复.
	 */
    @Action(value = "check_resource_name")
	public String checkResourceName() {
		HttpServletRequest request = ServletActionContext.getRequest();
		String newResourceName = request.getParameter("name");
		String oldResourceName = request.getParameter("oldResourceName");

		if (resourceManager.isResourceNameUnique(newResourceName, oldResourceName)) {
			Struts2Utils.renderText("true");
		} else {
			Struts2Utils.renderText("false");
		}
		//因为直接输出内容而不经过jsp,因此返回null.
		return null;
	}

	public Resource getModel() {
		return resource;
	}

	/* getter & setter */
	public void setId(Long id) {
		this.id = id;
	}

	public Page<Resource> getPage() {
		return page;
	}

	public String getAuthNames() {
		return authNames;
	}

	public void setAuthNames(String authNames) {
		this.authNames = authNames;
	}

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

}
